package code.ws_common_scene.map
{
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	import starling.display.Image;
	import starling.display.Sprite;
	import starling.textures.Texture;
	import starling.utils.Color;

	/**
	 * 加载地图切片工具 
	 * @author qiangchen
	 * （切片大小需满足context3D渲染要求，既满足DirectX也许满足openGL。尺寸为：
	 * 1X1,2X2,4X4,8X8,16X16,32X32,64X64,128X128,256X256,512X512,1024X1024,2048X2048；
	 * 此处定为512*512大小）
	 */	
	public class MapSlice extends Sprite
	{
		/** 切片大小 */
		private const slice_size:int = 512;
		
		
		/**
		 * 构造函数 
		 * 
		 */		
		public function MapSlice()
		{
		}
		
		
		
		/**
		 * 重置
		 * 
		 */		
		public function reset():void
		{
			while( this.numChildren )
			{
				( this.getChildAt( 0 ) as Image ).texture.dispose();
				this.removeChildAt( 0, true );
			}
		}
		
		
		
		/**
		 * 生成地图切片 
		 * @param bmp
		 * 
		 */		
		public function analyze( bmp:BitmapData ):void
		{
			var col:int = ( bmp.width % slice_size == 0 ) ? bmp.width / slice_size : bmp.width / slice_size + 1;
			var row:int = ( bmp.height % slice_size == 0 ) ? bmp.height / slice_size : bmp.height / slice_size + 1;
//			trace( col, row );
			var rect:Rectangle = new Rectangle();
			var p:Point = new Point(0,0);
			for( var i:int=0; i<col; i++ )
			{
				for( var j:int=0; j<row; j++ )
				{
					var _bmp:BitmapData = new BitmapData( slice_size, slice_size, false, Color.BLACK );
					rect.setTo( i * slice_size, j * slice_size, slice_size, slice_size );
					_bmp.copyPixels( bmp, rect, p );
					
					// 创建位图
					var img:Image = new Image( Texture.fromBitmapData( _bmp ) );
					img.x = i * slice_size;
					img.y = j * slice_size;
					addChild( img );
					_bmp.dispose();
					_bmp = null;
				}
			}
			p = null;
			rect = null;
			col = NaN;
			row = NaN;
			bmp.dispose();
			bmp = null;
		}
		
		
		/**
		 * 释放 
		 * 
		 */		
		override public function dispose():void
		{
			reset();
			super.dispose()
		}
	}
}